package com.lanhao.aot.carrierintegration.uspeed;

import java.util.Map;

import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;
import com.beust.jcommander.internal.Maps;
import com.lanhao.aot.carrierintegration.AeIfRequestDTO;
import com.lanhao.aot.carrierintegration.Warehouse;

import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpRequest;

public class USpeedInvokeUtil {
	private static final Logger LOG = LoggerFactory.getLogger(USpeedInvokeUtil.class);
	
	// 正式环境参数
	public static final String BASE_URL = "http://express.u-speedex.com/prod-api";
	public static final String USERNAME = "BJAH01";
	public static final String PASSWORD = "000000";
	
	// 测试环境参数
//	public static final String BASE_URL = "http://testuspeedorder.importgogo.com/prod-api";
//	public static final String USERNAME = "Anhe";
//	public static final String PASSWORD = "Anhe123";
	
	public static final String LOGIN_URL = BASE_URL + "/system/api/login";
	public static final String ORDER_URL = BASE_URL + "/willReturnOrderPush";
	public static final String FETCH_URL = BASE_URL + "/fetchLabel";
	public static final String QUERY_TRACKINGNO_URL = BASE_URL + "/queryOrder";
	
	public static final Double DEFAULT_WEIGHT = 0.1d;
	public static final String CARRIER_KR = "CJ Logistics";
	public static final String CARRIER_US = "USPS";
	public static final String FILE_TYPE = "PDF";

	public static final String COUNTRY_CODE_KR = "KR";
	public static final String COUNTRY_CODE_US = "US";
	
	public static void main(String[] args) {
		Pair<Boolean, String> ifToken = getIfToken();
		LOG.info("获取USpeed认证token，返回结果：token={}", ifToken);
		String countryCode = COUNTRY_CODE_KR;
		AeIfRequestDTO request = new AeIfRequestDTO();
		request.setCountry_code(countryCode);
		request.setShipper_country_code(countryCode);
		Warehouse warehouse = new Warehouse();
		warehouse.setNationCode(countryCode);
		
		if(COUNTRY_CODE_KR.equals(countryCode)) {
			request.setShipper_city("부천시");
			request.setShipper_name("김학송");
			request.setShipper_phone("01086821314");
			request.setWarehouse_code("CK" + countryCode + "000001");
			request.setShipper_post_code("14696");
			request.setShipper_province("경기도");
			request.setShipper_street("괴안동 40-11, 화성연립 제씨동 202호");
			
			warehouse.setCity("정왕동");
			warehouse.setPhone("01093255768");
			warehouse.setPostCode("15039");
			warehouse.setReceiver("KR-RTN-AE");
			warehouse.setState("경기도");
			warehouse.setStreet("중심상가로74");
			warehouse.setWarehouseCode("CK" + countryCode + "000001");
		} else if(COUNTRY_CODE_US.equals(countryCode)) {
			request.setShipper_city("San Mateo");
			request.setShipper_name("KunKun");
			request.setShipper_phone("4085684260");
			request.setWarehouse_code("CK" + countryCode + "000001");
			request.setShipper_post_code("94401");
			request.setShipper_province("CA");
			request.setShipper_street("1424 Newbridge Ave, Sunny Island Group LLC");
			
			warehouse.setCity("San Mateo");
			warehouse.setPhone("4085684260");
			warehouse.setPostCode("94401");
			warehouse.setReceiver("US-RTN-AE");
			warehouse.setState("CA");
			warehouse.setStreet("1500 Newbridge Ave, Sunny Island Group LLC");
			warehouse.setWarehouseCode("CK" + countryCode + "000001");
		}
		
//		createOrder(request, warehouse, ifToken);
		
		
		queryTrackingNo("KR231103794X6", ifToken);
	}
	
	public static Pair<Boolean, String> getIfToken() {
		JSONObject request = new JSONObject();
		request.put("username", USERNAME);
		request.put("password", PASSWORD);
		LOG.info("调用USpeed登录认证接口，url={}，request={}", LOGIN_URL, request.toJSONString());
		String response = HttpRequest.post(LOGIN_URL).timeout(3000).body(request.toJSONString()).execute().body();
		LOG.info("调用USpeed登录认证接口返回结果response={}", response);
		if (StringUtils.isNotBlank(response)) {
			JSONObject respObject = JSON.parseObject(response);
			int code = respObject.getIntValue("code");
			String msg = respObject.getString("msg");
			String token = respObject.getString("token");
			if (code == 200) {
				if (StringUtils.isNotBlank(token)) {
					return Pair.of(Boolean.TRUE, token);
				}
				return Pair.of(Boolean.FALSE, "token信息为空");
			}
			return Pair.of(Boolean.FALSE, msg);
		}
		return Pair.of(Boolean.FALSE, "调用Login接口无响应");
	}
	
	
	public static Pair<Boolean, String> createOrder(AeIfRequestDTO afRequest, Warehouse warehouse, Pair<Boolean, String> ifToken) {
		
		if (!ifToken.getLeft()) {
			return Pair.of(Boolean.FALSE, ifToken.getRight());
		}
		
		String token = ifToken.getRight();
		
		JSONObject request = new JSONObject();
		// 收件人信息
		request.put("addresseeName", warehouse.getReceiver());
		request.put("addresseeProvince", warehouse.getState());
		request.put("addresseeCity", warehouse.getCity());
//		request.put("addresseeArea", "");
		request.put("addresseeStreet", warehouse.getStreet());
		request.put("addresseePhone", warehouse.getPhone());
		request.put("addresseePostcode", warehouse.getPostCode());
		// 发件人信息
		request.put("shipperName", afRequest.getShipper_name());
		request.put("shipperProvince", afRequest.getShipper_province());
		request.put("shipperCity", afRequest.getShipper_city());
//		request.put("shipperArea", "");
		request.put("shipperStreet", afRequest.getShipper_street());
		request.put("shipperPhone", afRequest.getShipper_phone());
		request.put("shipperPostcode", afRequest.getShipper_post_code());
		String taskNo = UUID.fastUUID().toString(true);
		// 其他信息
		request.put("taskNo", taskNo);
		request.put("country", afRequest.getCountry_code());
		request.put("log_type", "1");
		request.put("flgOnShelf", "0");
		
		// 包裹信息
		JSONObject parcel = new JSONObject();
		parcel.put("weight", DEFAULT_WEIGHT);
		parcel.put("weightUnit", "KG");
		parcel.put("length", 10);
		parcel.put("width", 10);
		parcel.put("height", 10);
		parcel.put("sizeUnit", "CM");
		parcel.put("value", 0.01);
		parcel.put("currency", "USD");
		if(COUNTRY_CODE_KR.equals(afRequest.getCountry_code())) {
			parcel.put("method", "DOOR");  // 韩国是DOOR  美国是SP （网点）
		} else {
			parcel.put("method", "SP");  // 韩国是DOOR  美国是SP （网点）
		}
		parcel.put("platform", "ALIEXPRESS");
		parcel.put("company", "");
		parcel.put("flgBuyInsure", "");
		parcel.put("sumInsured", "");
		parcel.put("currencyInsured", "");
		
		request.put("parcel", parcel);
		
		JSONArray goods = new JSONArray();
		JSONObject good = new JSONObject();
		good.put("itemCode", "TEMURETRUN");
		good.put("itemType", "TEMURETRUN");
		good.put("itemDesc", "TEMURETRUN");
		good.put("itemImgUrl", "https://res-oss.anhelogistics.com/image/AnHeGoods.png");
		good.put("putawayFlag", "");
		good.put("weightSummed",DEFAULT_WEIGHT);
		good.put("weightUnit", "KG");
		good.put("length", 10);
		good.put("width", 10);
		good.put("height", 20);
		good.put("sizeUnit", "CM");
		good.put("volumeSummed", "");
		good.put("unitPrice", 0.01);
		good.put("currency", "USD");
		good.put("itemQuantity", 1);
		good.put("disposal", "DESTROY");
		good.put("goodsUrl", "https://res-oss.anhelogistics.com/image/AnHeGoods.png");
		good.put("flgCharged", "N");
		good.put("flgHazardous", "N");
		good.put("reason", "other");
		good.put("itemProofImgUrl", "https://res-oss.anhelogistics.com/image/AnHeGoods.png");
		good.put("itemDescZh", "");
		good.put("hsCode", "");
		good.put("color", "");
		good.put("origin", "");
		good.put("brand", "");
		good.put("model", "");
		good.put("material", "");
		good.put("flgMagnetic", "N");
		good.put("flgLiquid", "N");
		good.put("flgBreakable", "N");
		
		goods.add(good);
		
		request.put("Goods", goods);
		
		Map<String, String> headerMap = Maps.newHashMap();
		headerMap.put("Authorization", "Bearer " + token);
		LOG.info("调用USpeed创建订单接口，url={}，headerMap={}， request={}", ORDER_URL, JSON.toJSONString(headerMap),
				request.toJSONString());
		String response = HttpRequest.post(ORDER_URL).timeout(15000).addHeaders(headerMap).body(request.toJSONString()).execute().body();
		LOG.info("调用USpeed创建订单接口，返回信息response={}", response);
		// {"failCause":"获取成功","failCode":"200","content":{"documentNo":"92001901755477300460333881","secretKey":"","documentUrl":"https://yunjintong.oss-cn-beijing.aliyuncs.com/yspFile/CLExpressUrl/92001901755477300460333881.pdf","company":"USPS"},"status":"SUCCESS"}
		// {"failCause":"获取成功","failCode":"200","content":{"documentNo":"KR231000007X6","secretKey":"","documentUrl":"https://yunjintong.oss-cn-beijing.aliyuncs.com/yspFile/KRExpressUrl/KR231000007X6.pdf","company":"CJ logistics"},"status":"SUCCESS"}
		return null;
	}
	
	public static void queryTrackingNo(String waybillNo, Pair<Boolean, String> ifToken) {
		Map<String, String> headerMap = Maps.newHashMap();
		headerMap.put("Authorization", "Bearer " + ifToken.getRight());
		JSONObject request = new JSONObject();
		request.put("waybillNo", waybillNo);
		String response = HttpRequest.post(QUERY_TRACKINGNO_URL).timeout(15000).addHeaders(headerMap).body(request.toJSONString()).execute().body();
		LOG.info("查询真实物流单返回结果response={}", response);
		// {"msg":null,"code":200,"express2":"831100088861","waybillNo":"KR231000010X6"}  查询成功
		// {"msg":"查询结果为空","code":"200","documentUrl":"","taskNo":"","company":"","waybillNo":""} 转单号不存在
		// {"msg":null,"code":200,"express2":null,"waybillNo":"KR231103794X6"} 尚未取件寄送
	}
}
